home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c,comp.lang.c++
- Subject: Re: returning an array from function
- Date: 3 Apr 1996 11:11:25 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4juigtINNrus@keats.ugrad.cs.ubc.ca>
- References: <4jstd8$kh0@news1.sunbelt.net>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4jstd8$kh0@news1.sunbelt.net>,
- Rick Huebner <bourne@infoave.net> wrote:
- >I have looked in several texts and looked through the faq for this question
- >and can't find a reference for my answer. I am trying to return an array, or
-
- The FAQ discusses arrays and pointers at length, something that is crucial to
- C. I suspect you are scanning through it for an example of an array being
- passed to and returned from a function. However, a careful reading will teach
- you that this cannot be done.
-
- You cannot return arrays from functions nor pass them into functions. Nor can
- you assign directly to arrays (you can _initialize_ arrays but initialization
- is different from assignment).
-
- >a pointer to the array, from a function. I have seen several examples of
- >returning a pointer, but it doesn't seem to work for me. My function is going
- >to return an array of integers where 1-80 of them will be significant. The
- >calling function will know how many integers are expected and will read them
- >off the array....If I can get the pointer back to the array. A friend of mine
- >told me to just make the array a global, but I don't want to do that if I can
- >help it. I would even resort to a recursive function that will pass the
- >integers back one at a time if that is possible. Does anyone have any
- >suggestions? I am open to anything and will go looking if you can tell me
- >where(hopefully online somewhere).
-
- It's not clear what you want. If you want the function to do something to your
- array, why would you care about the pointer? Its value is not surprising---it
- is just the address of element 0.
-
- The only reason for wanting to pass arrays by value to a function would be to
- have the function operate on its own _copy_ of the array rather than the
- original object. C doesn't have this, but it does allow structure passing. If
- you make your array part of a structure, you can do it:
-
- struct myarray {
- int x[40];
- }
-
- int compute_something(struct myarray M)
-
- {
- /* do something with M.x[] */
-
- return 0;
- }
-
- The function compute_something() gets its own copy of the structure, and
- therefore its own private copy of the array to work on. This can be wasteful,
- especially if the function doesn't really need a private copy of the array.
-
- If you want to protect yourself against accidentally modifying an array in a
- function that isn't supposed to, try using ``const'':
-
- int compute_something(const int arr[]);
-
- --
-
-